﻿# -*- coding: utf-8 -*-
# Add parent folder to sys.path, so we can import boot.
# App Engine causes main.py to be reloaded if an exception gets raised
# on the first request of a main.py instance, so don't add parent_dir multiple
# times.

#--------------
from DBController import *
from waveapi import robot
from waveapi import appengine_robot_runner
from google.appengine.api import memcache
from django.shortcuts import render_to_response
from django.template import loader, RequestContext

import passwords, logging

def printwavelist(has_changes = False, tags_updated = False):
  message = None
  if has_changes or tags_updated:      
    myRobot = robot.Robot(passwords.ROBOT_NAME,
      image_url = passwords.IMAGE_URL,
      profile_url = passwords.PROFILE_URL)
    myRobot.setup_oauth(passwords.CONSUMER_KEY, passwords.CONSUMER_SECRET, server_rpc_base='http://www-opensocial.googleusercontent.com/api/rpc')
    appengine_robot_runner.run(myRobot)
    if tags_updated:
      db_controller = DBController()
      if not memcache.set("db_controller", db_controller):
        memcache.add("db_controller", db_controller)
    else:
      db_controller = memcache.get("db_controller")
      if not db_controller:
        db_controller = DBController()
        memcache.add("db_controller", db_controller, 600)    
    wave_catalog = db_controller.get_all()
    for i in db_controller.subtags:
      try:
          header = db_controller.subtags[i]["header"] + "\n"
          text = unicode(wave_catalog[i])
          new_text = header + text
          wave_list = myRobot.fetch_wavelet(wave_id = db_controller.subtags[i]["wave_id"].strip(), wavelet_id="googlewave.com!conv+root")  
          root_blip = wave_list.root_blip
          old_text = root_blip.text.strip()
          if old_text != new_text.strip():
            root_blip.all().delete()
            root_blip.append(header)
            if len(text) > 0
              root_blip.append(text)
              header_length = len(header)
              annotation_list = wave_catalog[i].annotation
              blip_ref = root_blip.range(header_length, len(root_blip.text))
              blip_ref.clear_annotation("conv/title")
              blip_ref.annotate("style/fontWeight", "bold")
              for annotation in annotation_list:
                blip_ref = root_blip.range(annotation["range"]["begin"] + header_length, annotation["range"]["end"] + header_length)    
                blip_ref.clear_annotation("style/fontWeight")
                blip_ref.annotate(annotation["key"], annotation["value"])    
          myRobot.submit(wave_list)
      except:
          logging.error("Could not fetch wavelet %s" % db_controller.subtags[i]["wave_id"])         
    has_changes = False
    message = u'Catalog has been updated.'
    if not memcache.set("has_changes", has_changes):
      logging.error("Memcache [has_changes] set failed.")
      message += u' Memcache [has_changes] set failed.'
  else:
    message = u"No changes applied."
  return message

def print_wave_list(request = None):
  has_changes = memcache.get("has_changes")
  if has_changes: #request.user.is_authenticated()
    message = printwavelist(has_changes)    
  else:
    message = u"There are no changes!"
  if request:
    return render_to_response('index.html',
                              {'err': message},
                              RequestContext(request))        